<?php
	function IPtoCountry($IP) 
	{
		
		$IP = sprintf('%u',IP2Long($IP));
		
        $query = "SELECT country_code2 FROM ip_country WHERE IP_from <= $IP AND IP_to >= $IP LIMIT 1";
		
		$result = mysql_query($query);
	
		if(mysql_num_rows($result) == 0) 
		{
			$country = "--";
		} 
		else 
		{
			$row = mysql_fetch_object($result);
			$country = $row->country_name;
		}
	
		return $country;
	}

    function getIP() {
        $ip = "";
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } 
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;            
    } 

	function logUserAction()
	{
        $command = "--"; 
        if (isset($_POST['command'])) 
            $command = strtolower($_POST['command']);

        if (
               ($command == 'user_login') ||
               ($command == 'user_logout') ||
               ($command == 'new_comment') ||
               ($command == 'rate_comment') ||
               ($command == 'register_new_user') ||
               ($command == 'update_page_rating') ||
               ($command == 'add_tag') ||
               ($command == 'rate_tag') ||
               ($command == 'delete_tag') ||
               ($command == 'get_pages_with_tag') ||
               ($command == 'follow_contact') ||
               ($command == 'unfollow_contact') ||
               ($command == 'add_link') ||
               ($command == 'rate_link') 
            )
        {
            $IP = getIP();

            $user_id = -1;  
            if (isset($_SESSION['user_id'])) {
                $user_id = $_SESSION['user_id'];
            }
            else {
                if (isset($_POST['user_name'])) {
                    $user_name = $_POST['user_name'];
                
                    $query = "SELECT id FROM User WHERE name = '" . $user_name . "'";
                    $result = mysql_query($query);
                
                    if (mysql_num_rows($result) != 0) {
                        $result_row = mysql_fetch_assoc($result);
                        $user_id = $result_row['id'];
                    }   
                }
            }
            
            $country = IPtoCountry($IP);
        
            $query = "INSERT INTO ActivityLog (user_id, command, ip, country_code2) VALUE ('$user_id', '$command', '$IP', '$country')";
            $result = mysql_query($query);
        }
    }
	




?>
